package com.ly.hotel.spainterface.jxd.dialog;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.jg.view.CustomToast;
import com.ly.hotel.spainterface.jxd.adapter.JxdJSItemAdapter;
import com.ly.hotel.spainterface.jxd.adapter.JxdJSSexAdapter;
import com.ly.hotel.spainterface.jxd.bean.MachineBean;
import com.ly.hotel.spainterface.jxd.bean.Massage;
import com.ly.hotel.spainterface.jxd.bean.PluginBean;
import com.ly.hotel.spainterface.jxd.bean.Therapy;
import com.ly.hotel.spainterface.jxd.utils.AvoidDoubleClickedUtils;
import com.ly.hotel.spainterface.jxd.utils.UdpUtils;
import com.ly.hotel.spainterface.jxd.utils.XmlParseUtils;
import com.ly.hotel.util.ProcessWaitingUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by ThinkPad on 2018/3/26.
 */

public class JxdRecommendDialog extends DialogFragment {

    private Context context;
    private ImageButton recommendClose;
    private GridView recommendSelectItem;
    private GridView recommendSelectSex;
    private Button recommendTherapy;
    private final int GET_HALL_ITEM = 1;
    private final int GET_THERAPY_DATA = 2;
    private final int GET_THERAPY_DATA_BY_ARTNO = 8;
    private final String TAG = "JxdJSActivity";
    private TextView noHallDataTips;
    private String sex;
    private String massageTypeNo;
    private MachineBean machineBean;
    private PluginBean pluginBean;
    private String artNo;
    private View view;
    private String massageName;
    private List<Massage> hallMassage = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = MyApplication.getContext();
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            // 设置Dialog宽度占比为60%，高度为wrap_content
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.64), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        /*Window window = dialog.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.windowAnimations = R.style.customDialogAnim;
        window.setAttributes(layoutParams);*/
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        view = LayoutInflater.from(context).inflate(R.layout.jxd_recommend_layout,container,false);
        initView();
        //getHallItem();
        setHallItem();
        setSexItem();
        setArrangeButton();

        return view;
    }

    // 初始化View
    public void initView(){
        recommendClose = view.findViewById(R.id.recommend_dialog_close);
        recommendSelectItem = view.findViewById(R.id.recommend_select_item);
        recommendSelectSex = view.findViewById(R.id.recommend_select_sex);
        recommendTherapy = view.findViewById(R.id.recommend_therapy);
        noHallDataTips = view.findViewById(R.id.cannot_get_hall_data);
        recommendClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    // 设置大堂项目
    private void setHallItem() {
        if(hallMassage.size() == 0){
            noHallDataTips.setVisibility(View.VISIBLE);
        }else{
            final JxdJSItemAdapter itemAdapter = new JxdJSItemAdapter(context,hallMassage);
            recommendSelectItem.setAdapter(itemAdapter);
            recommendSelectItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    itemAdapter.setDefaultPositon(position);
                    Massage massage = hallMassage.get(position);
                    massageName = massage.getMassagename();
                    setMassageTypeNo(massage.getMassagetypeno());
                    Log.i(TAG,"massageTypeNo=" + massageTypeNo);
                    itemAdapter.notifyDataSetChanged();
                }
            });
            recommendSelectItem.performItemClick(recommendSelectItem.getChildAt(0),0,recommendSelectItem.getItemIdAtPosition(0));
        }
    }

    // 设置选性别
    public void setSexItem(){
        // 设置选性别
        final List<String> sexList = new ArrayList<>();
        sexList.add("女");
        sexList.add("男");
        sexList.add("全部");
        final JxdJSSexAdapter sexAdapter = new JxdJSSexAdapter(context,sexList);
        recommendSelectSex.setAdapter(sexAdapter);
        recommendSelectSex.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sexAdapter.setDefaultPositon(position);
                setSex(sexList.get(position));
                sexAdapter.notifyDataSetChanged();
            }
        });
        recommendSelectSex.performItemClick(recommendSelectSex.getChildAt(0),0,recommendSelectSex.getItemIdAtPosition(0));
    }

    public void setArrangeButton(){
        // 推荐技师
        recommendTherapy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AvoidDoubleClickedUtils.isNotDoubleClicked()){
                    return;
                }
                getRecommendTherapy();
            }
        });
    }

    // 获取大堂项目数据
    public void getHallItem(){
        String req = "<gs ver=\"1.0\" function=\"桑拿做钟类型\" mode = \"request\"><MassageTypeNo>" +
                "</MassageTypeNo><MassageName></MassageName><IsHall>1</IsHall><OnlyMassageName>0</OnlyMassageName>" +
                "<SpecSetting>1</SpecSetting></gs>";
        UdpUtils udpUtils = new UdpUtils();
        udpUtils.getUdpResult(pluginBean.getIp(),pluginBean.getPort(),req,handler,GET_HALL_ITEM);
    }

    // 请求技师数据
    public void getTherapyDataByArtNo(String artNo){
        Log.i(TAG,"推荐的技师号：" + artNo);
        String req = "<gs ver=\"1.0\" function=\"技师资料查询\" mode = \"request\"><ArtNo>" + artNo + "</ArtNo><Status>" +
                "</Status><Onduty></Onduty><ArtModeNo></ArtModeNo><Columns></Columns><ArtTypeNo>" +
                "</ArtTypeNo></gs>";
        UdpUtils udpUtils = new UdpUtils();
        udpUtils.getUdpResult(pluginBean.getIp(),pluginBean.getPort(),req,handler,GET_THERAPY_DATA_BY_ARTNO);
    }

    // 获取推荐技师数据
    public void getRecommendTherapy(){
        String sexNum = "0";
        if(sex.equals("女")){
            sexNum = "0";
        }else if(sex.equals("男")){
            sexNum = "1";
        }else if(sex.equals("全部")){
            sexNum = "-1";
        }
        if(TextUtils.isEmpty(massageTypeNo)){
            CustomToast customToast = CustomToast.makeText(context,getResources().getString(R.string.please_select_item), Toast.LENGTH_SHORT,false);
            customToast.setGravity(Gravity.CENTER,0,0);
            customToast.show();
        }else{
            ProcessWaitingUtil.showProcessDialog(context,getResources().getString(R.string.loading_tips),10000);
            String req = "<gs ver=\"1.0\" function=\"桑拿技师推荐\" mode = \"request\"><JgFlag></JgFlag>" +
                    "<MTypeNo>" + massageTypeNo + "</MTypeNo><Sex>" + sexNum + "</Sex></gs>";
            UdpUtils udpUtils = new UdpUtils();
            udpUtils.getUdpResult(pluginBean.getIp(),pluginBean.getPort(),req,handler,GET_THERAPY_DATA);
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    Log.i(TAG,"接口返回：" + msg.obj.toString());
                    String resultString = msg.obj.toString();
                    if(msg.arg1 == GET_THERAPY_DATA){
                        if(resultString.startsWith("Msg") || TextUtils.isEmpty(resultString)){
                            Log.i(TAG,"没有获取到推荐技师数据");
                            ProcessWaitingUtil.closeProcessDialog();
                            if(TextUtils.isEmpty(resultString)){
                                CustomToast customToast = CustomToast.makeText(context,
                                        getResources().getString(R.string.connect_err),Toast.LENGTH_SHORT,false);
                                customToast.setGravity(Gravity.CENTER,0,0);
                                customToast.show();
                            }else{
                                CustomToast customToast = CustomToast.makeText(context,getResources().getString(R.string.no_thchnician_recommend), Toast.LENGTH_SHORT,false);
                                customToast.setGravity(Gravity.CENTER,0,0);
                                customToast.show();
                            }
                        }else{
                            List<Therapy> therapies = XmlParseUtils.getInstance().parseTherapy(resultString);
                            if(therapies.size() > 0){
                                Therapy therapy = therapies.get(0);
                                artNo = therapy.getArtNo();
                                getTherapyDataByArtNo(artNo);
                            }
                        }
                    }else if(msg.arg1 == GET_THERAPY_DATA_BY_ARTNO){
                        ProcessWaitingUtil.closeProcessDialog();
                        if(resultString.startsWith("Msg") || TextUtils.isEmpty(resultString)){
                            CustomToast customToast = CustomToast.makeText(context,getResources().getString(R.string.connect_err),Toast.LENGTH_SHORT,false);
                            customToast.setGravity(Gravity.CENTER,0,0);
                            customToast.show();
                        }else{
                            List<Therapy> therapyList = XmlParseUtils.getInstance().parseTherapy(resultString);
                            if(therapyList.size() > 0){
                                setDialog(therapyList);
                            }else{
                                CustomToast customToast = CustomToast.makeText(context,getResources().getString(R.string.connect_err),Toast.LENGTH_SHORT,false);
                                customToast.setGravity(Gravity.CENTER,0,0);
                                customToast.show();
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void setDialog(List<Therapy> therapies){
        JxdJSDetailDialog detailDialog = new JxdJSDetailDialog();
        detailDialog.setPluginBean(pluginBean);
        detailDialog.setMachineBean(machineBean);
        detailDialog.setTherapies(therapies);
        detailDialog.setArrangeTimeOut(pluginBean.getArrangeTimeOut());
        detailDialog.setIsSpec("轮牌");
        detailDialog.setIsHall("是");
        detailDialog.setArtNo(artNo);
        detailDialog.setMassageName(massageName);
        detailDialog.setCancelable(false);
        detailDialog.show(getFragmentManager(),"JxdJSDetailDialog");
        EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_JISHI + "\t" +
                MyApplication.interfaceVersion + "\t" + "推荐技师" + "\t" + massageName));
        dismiss();
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setMassageTypeNo(String massageTypeNo) {
        this.massageTypeNo = massageTypeNo;
    }

    public void setMachineBean(MachineBean machineBean) {
        this.machineBean = machineBean;
    }

    public void setPluginBean(PluginBean pluginBean) {
        this.pluginBean = pluginBean;
    }

    public void setHallMassage(List<Massage> hallMassage) {
        this.hallMassage = hallMassage;
    }
}
